package com.zj.util;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class PhoneNoHandler extends BaseTypeHandler<List<String>> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List<String> strings, JdbcType jdbcType) throws SQLException {
        String phoneNos=dealListToOneStr(strings);
        preparedStatement.setString(i , phoneNos);
    }

    @Override
    public List<String> getNullableResult(ResultSet resultSet, String s) throws SQLException {
        String nos=resultSet.getString(s);
        return dealOneStrToList(nos);
    }

    @Override
    public List<String> getNullableResult(ResultSet resultSet, int i) throws SQLException {
        String nos=resultSet.getString(i);
        return dealOneStrToList(nos);
    }

    @Override
    public List<String> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        String nos=callableStatement.getString(i);
        return dealOneStrToList(nos);
    }


    private String dealListToOneStr(List<String> parameter){
        if(parameter == null || parameter.size() <=0)
            return null;
        StringBuilder res = new StringBuilder();
        for (String s1:parameter) {
            res.append(s1).append(",");
        }
        return res.substring(0,res.length()-1);
    }

    private List<String> dealOneStrToList(String parameter) {
        if (parameter == null || parameter.length() <= 0)
            return null;
        String[] strs = parameter.split(",");
        return Arrays.asList(strs);
    }
}
